from flask import Blueprint, jsonify, request, render_template, redirect, url_for
from pymongo import MongoClient
from bson import ObjectId

python_exercises_bp = Blueprint('python_exercises', __name__)

# MongoDB连接
client = MongoClient('mongodb://localhost:27017/')
db = client['fn_programme']
questions_collection = db['python_questions']
exams_collection = db['python_exams']

# 试卷类型映射
EXAM_TYPES = {
    'basic': '基础知识',
    'logic': '逻辑运用',
    'algorithm': '算法练习',
    'comprehensive': '综合测评'
}

@python_exercises_bp.route('/api/python/questions')
def get_questions():
    try:
        questions = list(questions_collection.find({}, {'_id': 0}))
        return jsonify(questions)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@python_exercises_bp.route('/exam_list/<level>')
def exam_list(level):
    try:
        # 构建查询条件
        query = {}
        if level != 'all':
            query['level'] = int(level)
        
        # 获取筛选参数
        exam_type = request.args.get('type', 'all')
        difficulty = request.args.get('difficulty', level if level != 'all' else 'all')
        
        if exam_type != 'all':
            query['type'] = exam_type
        if difficulty != 'all':
            query['difficulty'] = int(difficulty)
        
        # 从数据库获取试卷列表
        exams = list(exams_collection.find(query))
        
        # 处理试卷数据
        for exam in exams:
            exam['id'] = str(exam['_id'])
            del exam['_id']
            exam['type_display'] = EXAM_TYPES.get(exam['type'], '未知类型')
            
    except Exception as e:
        exams = []
    
    return render_template(
        'frontend/python_exam_list.html',
        level='全部' if level == 'all' else level,
        exams=exams
    )

@python_exercises_bp.route('/start_exam/<level>/<exam_id>')
def start_exam(level, exam_id):
    try:
        # 从数据库获取试卷信息
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if exam:
            exam['id'] = str(exam['_id'])
            del exam['_id']
            exam['type_display'] = EXAM_TYPES.get(exam['type'], '未知类型')
            return render_template(
                'frontend/python_exam.html',
                exam=exam,
                level=level
            )
    except Exception as e:
        pass
    
    # 如果试卷不存在，重定向到试卷列表
    return redirect(url_for('python_exercises.exam_list', level=level))

@python_exercises_bp.route('/api/python/submit', methods=['POST'])
def submit_answers():
    try:
        data = request.get_json()
        answers = data.get('answers', [])
        exam_id = data.get('exam_id')
        
        # 从数据库获取试卷和正确答案
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            raise Exception('试卷不存在')
            
        questions = exam.get('questions', [])
        total_questions = len(questions)
        correct_answers = 0
        
        # 检查答案
        for i, question in enumerate(questions):
            if i < len(answers):
                user_answer = answers[i]
                correct_answer = question.get('correct_answers', [])
                
                # 判断答案是否正确
                if isinstance(user_answer, list):
                    if sorted(user_answer) == sorted(correct_answer):
                        correct_answers += 1
                else:
                    if [user_answer] == correct_answer:
                        correct_answers += 1
        
        # 计算得分
        score = round(correct_answers / total_questions * 100, 2)
        
        return jsonify({
            'success': True,
            'score': score,
            'correct_answers': correct_answers,
            'total_questions': total_questions
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
